<?php
use Home\Model\CartModel;
use Hoteladmin\Model\AdminModel;
/**
 * 前端商城   公共函数模块的逻辑处理
 * ============================================================================
 * 版权所有 2018-2025 北京优特世纪科技有限公司，并保留所有权利。
 * 网站地址: http://www.unitewww.com;
 * ============================================================================
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * @since: 1.0
 * @version: 1.0
 **/
/**
 +--------------------------------------------------------------------------
 * 实现获取当前分类所有
 +--------------------------------------------------------------------------
 */
function getCateGrandson($caid){
    $GLOBALS['grandSon']= array();
    // 先把自己的id 保存起来
    $GLOBALS['grandSon'][] = $caid;
    $son_id_arr = M('category')->where("ca_parent = $caid")->cache(true)->getField('ca_id',true);
    foreach($son_id_arr as $k => $v){
        $GLOBALS['grandSon'][$k] = $v;
    }
    //dump($GLOBALS['grandSon']);
    return $GLOBALS['grandSon'];
}
/**
 +--------------------------------------------------------------------------
 * 获取商品库存
 * @param type $goid 商品id
 * @author XC跃
 +--------------------------------------------------------------------------
 */
function getGoodNum($goid){
    //实例化相关表
    $gident = M("goods");
    $stock = $gident->where("`go_id` ='".$goid."'")->getField('go_stock');
    return $stock;
}
/**
 +--------------------------------------------------------------------------
 * 实现添加运费计算的功能
 * @param type $addre  用户选择的收货地址
 * @param type $cList  选择购物列表
 * @author : ZJ
 * @date : 2018-09-19
 +--------------------------------------------------------------------------
 */
function freight($addre,$cList){
    //实例化相关表
    $frident = M('freight');
    //统计计算商品总重量
    foreach($cList as $key=>$val){
        //判断结算列表中是否含有免运费商品
        if('1'==$val['ca_free']){
            return 0;
        }else{
            $weight = round($val['ca_gnum']*$val['ca_weight']/1000,2);//将单位克转化为千克
            $weiSum += $weight; //所有商品的总重
        }
    }
    //echo $weiSum;
    //获取运费模板
    $frList = $frident->field("fr_region,fr_id")->select();
    foreach ($frList as $vals){
        $region = json_decode($vals['fr_region']);
        $region = implode(',', $region);
        //判断选择的城市在不在运费模板里
        if(strpos($region,$addre['ad_city'])==true){
            //dump($vals['fr_id']);
            $frFind = $frident->where("`fr_id` = '".$vals['fr_id']."'")->find();
            break;
        }else{
            $frFind = $frident->where("`fr_region` = '默认'")->find();
        }
    }
    //dump($frFind);
    //判断选中规格是否在首重范围内
    if($weiSum<=$frFind['fr_first_heavy']){
        $res = $frFind['fr_first_price'];
    }else{
        $add_heavy = ($weiSum - $frFind['fr_first_heavy'])/$frFind['fr_add_heavy'];
        $res = round(ceil($add_heavy)*$frFind['fr_add_price']+$frFind['fr_first_price'],2);
    }
    //echo $res;
    return $res;
}
/**
 +--------------------------------------------------------------------------
 * 计算订单金额
 * @param type $uid  用户id
 * @param type $cart_good  购买的商品
 * @param type $umoney 余额
 * @param type $points  积分
 * @param type $coupon 优惠券金额
 * @author : XC跃
 * @date : 2018-06-06
 +--------------------------------------------------------------------------
 */
function calculate_price($uid,$cart_good,$umoney,$addre){
    //实例化相关表
    $uident = M('user');
    $cident = M('cart');
    $gident = M('goods');
    $frident= M('freight');
    $usident = M('user');
    //实例化相关Model
    $cidentr= New CartModel();
    //获取运费
    $conf = tpCache('sIno');
    $yun_fee= freight($addre,$cart_good);
    //dump($yun_fee);
    //获取相关信息
    $usFind = $uident->where("`us_uid`='".$uid."'")->field('us_money')->find();
    if(empty($cart_good)){
        exit(json_encode(array('status'=>-1,'msg'=>'订单商品列表不能为空')));
    }
    //$cList[$key]['cart'] = $cident->where("`ca_uid`='".$uid."' and `ca_sid`='".$sval."' and `ca_check`=1")->select();
    foreach ($cart_good as $key=>$val){
        $cList[$key]['price'] = round($val['ca_gnum']*$val['ca_gmoney'],2);
        //$cList[$key]['score'] = goods_energy(round($val['ca_gnum']*goods_energy($val['ca_jmoney']),2));
        $cList[$key]['expen'] = $yun_fee;
        $cList[$key]['stock'] = getGoodNum($val['ca_gid']);// 最多可购买的库存数量
        if($cList[$key]['stock'] <= 0){
            exit(json_encode(array('status'=>-1,'msg'=>$cList[$key]['ca_gname']."库存不足,请重新下单")));
        }
        $anum += $val['ca_gnum'];  //商品数量
        $tot_fee += round($val['ca_gnum']*$val['ca_gprice'],2);  //商品价值
        $cut_fee += round($val['ca_gnum']*($val['ca_gprice']-$val['ca_gmoney']),2); //优惠金额
        $umoney = $sum_fee += round($val['ca_gnum']*$val['ca_gmoney'],2);  //实付金额
        $fen_fee += round($val['ca_gnum']*$val['ca_jmoney'],2);
    }
    //判断会员能量
//     if($usFind['us_energy'] < $fen_fee){
//         exit(json_encode(array('status'=>-1,'msg'=>"能量值不足，请调整购物车")));
//     }
    //判断会员余额
//     if($usFind['us_money'] < $umoney){
//         exit(json_encode(array('status'=>-1,'msg'=>"使用余额输入错误")));
//     }
    //价格计算
    $order_amount = $sum_fee + $yun_fee; // 应付金额 = 商品价格 + 物流费    
    //echo $order_amount;
    //$total_amount = round($sum_fee + $yun_fee,2); //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品   余额  优惠券
    $user = $usident->where("`us_uid`='".$uid ."'")->find();

    if($user['us_daili']==1){
    $result = array(
        'total_amount'=> $tot_fee, // 商品总价
        'order_amount'=> $order_amount, // 应付金额
        'order_energy'=> $fen_fee, // 应付积分
        'ship_price'  => $yun_fee,   // 物流费
        'umoney'      => $umoney,    // 使用余额
        'energy'      => $fen_fee,   // 使用积分
        'cart_goods'  => $cart_good, // 商品列表 多加几个字段原样返回
    );
    } elseif($user['us_daili']==4){
        $result = array(
          'total_amount'=> $tot_fee, // 商品总价
          'order_amount'=> $order_amount, // 应付金额
          'order_energy'=> $fen_fee, // 应付积分
          'ship_price'  => $yun_fee,   // 物流费
          'umoney'      => $umoney,    // 使用余额
          'energy'      => $fen_fee,   // 使用积分
          'cart_goods'  => $cart_good, // 商品列表 多加几个字段原样返回
        );
    } elseif($user['us_daili']==7){
        $result = array(
          'total_amount'=> $tot_fee, // 商品总价
          'order_amount'=> $order_amount, // 应付金额
          'order_energy'=> $fen_fee, // 应付积分
          'ship_price'  => $yun_fee,   // 物流费
          'umoney'      => $umoney,    // 使用余额
          'energy'      => $fen_fee,   // 使用积分
          'cart_goods'  => $cart_good, // 商品列表 多加几个字段原样返回
        );
    }else{
        $result = array(
          'total_amount'=> $tot_fee, // 商品总价
          'order_amount'=> $order_amount, // 应付金额
          'order_energy'=> $fen_fee, // 应付积分
          'ship_price'  => $yun_fee,   // 物流费
          'umoney'      => $umoney,    // 使用余额
          'energy'      => $fen_fee,   // 使用积分
          'cart_goods'  => $cart_good, // 商品列表 多加几个字段原样返回
        );
    }
    return $result; // 返回结果状态
}
/**
 +--------------------------------------------------------------------------
 * 支付完成修改订单
 * @param $batch 流水号
 * @param $type  支付方式
 * @author : XC跃
 * @date : 2018-06-06
 +--------------------------------------------------------------------------
 */
function update_pay_status($batch,$type){

    //echo $oc_id;
    $ptype = C('PAY_TYPE');//支付方式
    //实例化相关表
    $orident = M('order');
    $acident = M('account');
    $usident = M('user');
    $lidentr = new AdminModel();
    //获取系统参数
    $sms = tpCache("sMes.order");
    //找出对应的订单
    $orFind = $orident->where("`or_batch`='".$batch."'")->find();
    //如果这笔订单已经处理过了
    if(count($orFind)=='1' && $orFind['or_pstate']=='2'){
        return false;
    }
    //如果是报单订单
    if($orFind['or_type']==2 && $orFind['or_pstate']=='1'){
        $lidentr->shiFang($orFind);
    }
    //1、修改支付状态  已支付
    $odata['or_pstate']= '2';
    $odata['or_ptime'] = time();
    $odata['or_pname'] = $ptype[$type];
    $orident->where("`or_id`='".$orFind['or_id']."'")->save($odata);


    //3、添加财务明细记录
    $remark = '会员下单'.$ptype[$type].'支付';
//    accShopLog($orFind['or_uid'],$orFind['or_zmon']*-1,$orFind['or_jmon'],'0',$remark,$orFind['or_id'],$batch);
     if($type == 2){
         accShopLog($orFind['or_uid'],$orFind['or_zmon']*-1,'0',$orFind['or_jmon']*-1,'0',0,$remark,$orFind['or_id'],$batch);
     }else{
         accShopLog($orFind['or_uid'],'0','0',$orFind['or_jmon']*-1,'0',0,$remark,$orFind['or_id'],$batch);
     }
    //4、发送手机短信
    if($sms=='1'){
        $addre = unserialize($orFind['or_add']);
        $params['batch'] = substr($batch,-7);
        $params['consi'] = $addre['aname'];
        $resp = sendSms('6',$addre['phone'],$params,session_id());
    }
    //5、记录订单操作日志
    logOrder($orFind['or_id'],'2','订单由'.$ptype[$type].'付款，等待商家发货','付款成功');
}
/**
 +--------------------------------------------------------------------------
 * 实现收货地址的正反序化的功能
 * @param $msg 编译内容
 * @param $type 类型 1:正序化 2:反序化
 * @author XC跃
 * @date : 2018-06-06
 +--------------------------------------------------------------------------
 */
function addreSerialize($msg,$type){
    //实例化相关表
    $adident = M('address');
    if('1'==$type){
        $adFind = $adident->where("`ad_id`='".$msg."'")->find();
        $addre = array(
            'aname'=> $adFind['ad_name'],
            'phone'=> $adFind['ad_phone'],
            'addre'=> $adFind['ad_area'].$adFind['ad_addre'],
        );
        $res = serialize($addre);
    }else{
        $res = unserialize($msg);
    }
    return $res;
}
/**
 +--------------------------------------------------------------------------
 * 截取两个数之间的字符串
 +--------------------------------------------------------------------------
 */
function cut_str($str,$sign,$number){
    $array=explode($sign, $str);
    $length=count($array);
    if($number<0){
        $new_array=array_reverse($array);
        $abs_number=abs($number);
        if($abs_number>$length){
            return 'error';
        }else{
            return $new_array[$abs_number-1];
        }
    }else{
        if($number>=$length){
            return 'error';
        }else{
            return $array[$number];
        }
    }
}

/**
+--------------------------------------------------------------------------
 * 实现推荐人未报单自动查找上级
 * @param $pid  推荐人id
 * @author GH
+--------------------------------------------------------------------------
 * *///========
function do_putSetuser($pid){
    $usident= M('user');
    $uvident = M('user_vip');
    $uver = $uvident->where("`uv_uid`='" .$pid."'")->find();//推荐人的vip信息
    if($uver==null){
        $user = $usident->where("`us_uid`='" .$pid. "'")->find();
        return do_putSetuser($user['us_pid']);
    }else{
        return $uver;
    }
}
?>